<?php
/*
 * 前台车系显示类
 * @package    auto
 * @author     YuNian, mark
 * @copyright  Copyright (c) 2013 ixdcw team
 * @version    $Id: 4be7a643ffd9b9edfc609734d418e05f394a5c85 $
 */

/**
 * 车系显示类
 * Class AutoShowCar
 */
class AutoPicture {

	private static $_types;
	private static $_waiguanId = 546;
	private static $_guanfangtuId = 551;
	private static $_pn;
	private static $_pagesize = 16;

	private static function _getTable($carid) {
		return Table::autoPicture($carid);
	}

	private static function _getTypes() {
		if (!empty(self::$_types)) {
			return self::$_types;
		} else {
			self::$_types = AutoCategory::getCache(AutoCategory::TYPE_PICTURE);
			return self::$_types;
		}
	}

	/**
	 * 统计图片数量
	 * @param        $carid
	 * @param string $modelid
	 * @return null
	 */
	public static function getNum($carid,$modelid='') {
		global $db;
		$modelSql = '';
		if($modelid) $modelSql = " and amid in (0, $modelid) ";
		$sql = "select count(apid) as num from " . self::_getTable($carid) . " where arcid = $carid " . $modelSql;
		return $db->getVar($sql, 'num');
	}

	/**
	 * 统计未匹配车款的图片
	 * @param $carid
	 * @return null
	 */
	public static function getNoMatchModelNum($carid) {
		global $db;
		$sql = "select count(apid) as num from " . self::_getTable($carid) . " where arcid = $carid and amid=0";
		return $db->getVar($sql, 'num');
	}


	/**
	 * 获取所有的图片列表
	 * @param        $carid
	 * @param string $amid
	 * @param string $alid
	 * @return $this
	 */
	public static function getPictures($carid, $amid='',$alid='') {
		global $db,$items;
		$topTypes = self::_getTopTypes();
		$pn = new Pagination();
		$pagesize = 8;

		if($amid) $amidSql = " and amid in(0,$amid)";    //假如筛选条件成立

		//取出 arrchildid 用于筛选
		if($alid) foreach($topTypes as $val) if($val['arid'] == $alid) $alidInSql=$val['arrchildid'];

		//循环缓存， 将符合规则的数据 写入
		foreach ($topTypes as $key => $type) {

			//假如 类型筛选条件 不成立,
			if(!$alid) {
				$sqlPic = "select * from " . self::_getTable($carid) . " where arcid ={$carid} and alid in({$type['arrchildid']}) $amidSql limit 4";
				$sqlNum = "select count(apid) as num from " . self::_getTable($carid) . " where arcid ={$carid} and alid in({$type['arrchildid']}) $amidSql";
				$topTypes[$key]['pics'] = $db->getAll($sqlPic);
				$topTypes[$key]['num']  = $db->getVar($sqlNum, 'num');
			}else{
				if($type['arid'] == $alid){
					$sqlPic = "select * from " . self::_getTable($carid) . " where arcid ={$carid} and alid in($alidInSql) $amidSql ";
					$sqlPic .= " LIMIT " . ($pn->getPage() - 1) * $pagesize . ',' . $pagesize;
					$sqlNum = "select count(apid) as num from " . self::_getTable($carid) . " where arcid ={$carid}  and alid in($alidInSql) $amidSql";

					$topTypes[$key]['pics'] = $db->getAll($sqlPic);
					$topTypes[$key]['num']  = $db->getVar($sqlNum, 'num');
					$items = $topTypes[$key]['num'];
					break;
				}
			}
		}
		return $topTypes;
	}

	/**
	 * @param     $carid
	 * @param int $limit
	 * @return array
	 */
	public static function getThumbs($carid, $limit = 4) {
		global $db;
		$pids = AutoCategory::getCacheItem(AutoCategory::TYPE_PICTURE, self::$_waiguanId, 'arrchildid');
		$sqlPic = "select * from " . self::_getTable($carid) . " where arcid ={$carid} and alid in({$pids})order by listorder desc limit $limit ";
		$picsWaiguan = $db->getAll($sqlPic);
		if (!$picsWaiguan) {
			$pids = AutoCategory::getCacheItem(AutoCategory::TYPE_PICTURE, self::$_guanfangtuId, 'arrchildid');
			$sqlPic = "select * from " . self::_getTable($carid) . " where arcid ={$carid} and alid in({$pids})order by listorder desc limit $limit ";
			$picsGuanfang = $db->getAll($sqlPic);
			if (!$picsGuanfang) {
				$sqlPic = "select * from " . self::_getTable($carid) . " where arcid ={$carid} order by listorder desc limit $limit ";
				return $db->getAll($sqlPic);
			} else {
				return $picsGuanfang;
			}
		} else {
			return $picsWaiguan;
		}
	}

	/**
	 * 获取顶级分类
	 * @return $this
	 */
	private static function _getTopTypes() {
		return __(self::_getTypes())->filter(function ($type) {
			return $type['parentid'] == 0;
		});
	}


	/**
	 * 图片筛选条件:车款型号
	 * @param        $carId
	 * @param string $issale
	 * @return array
	 */
	public static function getPicModelSearch($carId,$issale='') {
		global $db,$num;
		$table = Table::name(Table::NAME_AUTO_MODEL);

		$issaleSql = '';
		if(isset($issale) && $issale!='') $issaleSql = " and issale=$issale";
		$sql = "select amid,name,year from $table where status=3 and arcid=$carId $issaleSql";
		$modelName = $db->getAll($sql);

		//统计 未匹配车款的 图片数量
		$belongSum = AutoPicture::getNoMatchModelNum($carId);

		foreach($modelName as $model) {
			$year = Auto::getName($model['year']);

			//获取当前车款的图片数量
			$picNum = AutoPicture::getNum($carId,$model['amid']);

			//假如为真, 写入数据
			if($picNum) {
				$searchType[$year][$model['amid']] = $model['name']."( $picNum 张)";
				$num += $picNum;
			}else{
				//假如没有, 将没有匹配车款的图片数量写入
				$searchType[$year][$model['amid']] = $model['name']."( $belongSum 张)";
			}
		}
		if(!$num) $num = $belongSum;    //统计在售或停售的数量
		return $searchType;
	}


	/**
	 * 图片筛选条件:车款类别
	 * @param        $carid
	 * @param string $amid
	 * @return $this
	 */
	public function getPicTypeSearch($carid,$amid='') {
		global $db;
		$topTypes = self::_getTopTypes();
		if($amid) $amidSql = " and amid in(0,$amid)";    //假如筛选条件成立

		foreach ($topTypes as $key => $type) {
				$sqlPic = "select * from " . self::_getTable($carid) . " where arcid ={$carid} and alid in({$type['arrchildid']}) $amidSql limit 1";
				$sqlNum = "select count(apid) as num from " . self::_getTable($carid) . " where arcid ={$carid} and alid in({$type['arrchildid']}) $amidSql";
				$topTypes[$key]['pics'] = $db->getAll($sqlPic);
				$topTypes[$key]['num']  = $db->getVar($sqlNum, 'num');
		}
		return $topTypes;
	}

	/**
	 * 获取预览图片所用到的数据
	 * @param        $carid
	 * @param string $amid
	 * @return $this
	 */
	public static function getPicturesShow($carid,$amid='') {
		global $db;
		$topTypes = self::_getTopTypes();

		$amidSql='';
		if($amid) $amidSql = " and amid=$amid";

		//循环缓存， 将符合规则的数据 写入
		foreach ($topTypes as $key => $type) {
			$sqlPic = "select * from " . self::_getTable($carid) . " where arcid ={$carid} $amidSql and alid in({$type['arrchildid']}) ";
			$sqlNum = "select count(apid) as num from " . self::_getTable($carid) . " where arcid ={$carid} $amidSql and alid in({$type['arrchildid']})";
			$topTypes[$key]['pics'] = $db->getAll($sqlPic);
			$topTypes[$key]['num']  = $db->getVar($sqlNum, 'num');
		}
		return $topTypes;
	}


	/**
	 * 获取图片信息
	 * @param $carid
	 * @param $pictureid
	 * @return array|null
	 */
	public static function getPicturesInfo($carid,$pictureid) {
		global $db;
		$sql = "select * from " . self::_getTable($carid) . " where apid=$pictureid ";
		return $db->getOne($sql);
	}


	/**
	 * 生成json文件
	 * @param     $carid
	 * @param int $amid
	 * @param int $pictureid
	 * @param int $alid
	 * @return array
	 */
	public static function getPicturesAPI($carid, $amid = 0, $pictureid = 0, $alid = 0) {
		global $db;
		$table    = self::_getTable($carid);
		$result   = array();
		$params   = array();
		$list     = array();
		$listIds  = array();
		$pictureListNum = 9;

		// 获取所有的图片ID
		$amidSql = $amid ? " and amid=$amid" : '';
		$alidSql = $alid ? " and alid=$alid" : '';
		$sql     = "select apid from " . $table . " where arcid = $carid " . $amidSql .$alidSql;
		$apids   = $db->getCol($sql, 'apid');

		// 没有图片id, 指定第一个为图片ID
		if (!$pictureid) {
			$pictureid = $apids[0];
		}

		// 图片分类id
		if (!$alid) {
			$alid = $db->getVar("select alid from ".$table ." where apid=".$pictureid, 'alid');
		}

		$type = __(self::_getTypes())->filter(function($item) use ($alid){
			return $item['arid'] == $alid;
		});
		if (count($type) ==1 ) $type = $type[0];

		$sql     = "select apid from " . $table . " where arcid = $carid " . $amidSql .' and alid in('.$type['arrchildid'].')';
		$apids   = $db->getCol($sql, 'apid');

		// 空的调用车系图
		if (empty($apids)) {
			$sql     = "select apid from " . $table . " where arcid = $carid and alid in({$type['arrchildid']})";
			$apids   = $db->getCol($sql, 'apid');
		}
		// 获取数量, 获取前一组的pid和后一组的pid
		$params['sum'] = count($apids);
		$apidsChunk = array_chunk($apids, 9);
		$chunkPos = 0;
		foreach($apidsChunk as $k => $ids) {
			if (in_array($pictureid, $ids) && empty($listIds)) {
				$chunkPos = $k;
				$prevkey = $k-1;
				$nextKey = $k+1;
				if ($apidsChunk[$prevkey]) {
					$params['prev'] = array_pop($apidsChunk[$prevkey]);
				} else {
					$params['prev'] = 0;
				}

				if ($apidsChunk[$nextKey]) {
					$params['next'] = array_shift($apidsChunk[$nextKey]);
				} else {
					$params['next'] = 0;
				}
				$listIds = $ids;
				$params['pos'] = array_search($pictureid, $listIds);
				$params['allPos'] = array_search($pictureid, $apids);
				$params['catId'] = $type['arid'];
			} else {
				continue;
			}
		}
		$startPos = $chunkPos * $pictureListNum;
		$sql = "select apid,title,imgurl from " . $table . " where apid in(".implode(',', $listIds).")";
		$rs = $db->query($sql);
		while($r = $db->fetchArray($rs)) {
			$list[] = array(
				'id' => $r['apid'],
				'pos' => ++$startPos,
				'url' => Picture::thumb($r['imgurl'], 155, 113),
				'picsrc' => Picture::thumb($r['imgurl'], 800, 600),
				'title' => $r['title'],
			);
		}

		$result['params'] = $params;
		$result['list']   = $list;
		return $result;
	}


	public static function getPn() {
		if (!empty(self::$_pn)) {
			return self::$_pn;
		} else {
			self::$_pn = new Pagination();
			self::$_pn->padding(false);
			self::$_pn->recordsPerPage(self::$_pagesize);
			return self::$_pn;
		}
	}


}